<?php

/**
 * 获取淘宝相关信息
 * File Name：TaobaoApi.php
 * File Encoding：UTF-8
 * File New Time：2014-5-10 11:35:35
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class TaobaoApi {

    //TaoAPI对象
    private $handier = null;
    //商品ID
    private $productId = 0;

    public function __construct() {
        Yii::import('ext.taoAPI.*');
        $this->handier = new TaoAPI();
    }

    /**
     * 链接淘宝api服务
     * @staticvar null $handier
     * @return \TaoAPI
     */
    static public function getInstance() {
        static $handier = NULL;
        if (empty($handier)) {
            $handier = new TaobaoApi();
        }
        return $handier;
    }

    /**
     * 设置商品id
     * @param type $productId
     * @return \TaobaoApi
     */
    public function productId($productId = 0) {
        $this->productId = $productId;
        return $this;
    }

    /**
     * 设置查询类型
     * @param type $method
     * @return \TaobaoApi
     */
    public function method($method = 'taobao.item.get') {
        if (empty($this->productId)) {
            throw new CException(Yii::t('yii', '{class} productId 不能为空.', array('{class}' => get_class($this))));
        }
        //商品数字ID
        if (in_array($method, array('taobao.item.get', 'taobao.taobaoke.items.detail.get'))) {
            $this->handier->num_iid = $this->productId;
        }
        if (in_array($method, array('taobao.ump.promotion.get'))) {
            $this->handier->item_id = $this->productId;
        }
        $this->handier->method = $method;
        return $this;
    }

    /**
     * 设置查询字段
     * @param type $fields
     * @return \TaobaoApi
     */
    public function fields($fields = 'detail_url,title,nick,location,item_img,price,pic_url') {
        $this->handier->fields = $fields;
        return $this;
    }

    /**
     * 获取数据
     * @return array
     */
    public function getData() {
        return $this->handier->Send('get', 'xml')->getArrayData();
    }

    /**
     * 根据商品id获取店铺类型
     * @param type $product_id 商品id
     * @return int 1为天猫，0为C点
     */
    public function getShopType($product_id) {
        $item_type = 0;
        if (empty($product_id)) {
            if (empty($this->productId)) {
                return $item_type;
            } else {
                $product_id = $this->productId;
            }
        }
        $json = $this->getHwsMobileTaobaoApi($product_id);
        if (is_array($json)) {
            if (is_array($json) && !empty($json)) {
                if (isset($json['data']['itemInfoModel']['itemTypeName'])) {
                    $itemTypeName = $json['data']['itemInfoModel']['itemTypeName'];
                    $item_type = $itemTypeName == 'tmall' ? 1 : 0;
                }
            }
        } else {
            $url = 'http://item.taobao.com/item.htm?id=' . $product_id;
            $html = $this->getTaoBaoHtml($url);
            //判断内容
            if (strlen(trim($html)) > 10000) {
                preg_match_all('/.*?<title>(.*?)<\/title>/is', $html, $out, PREG_PATTERN_ORDER);
                $title = iconv("gb2312", "utf-8//IGNORE", $out[1][0]);
                if (isset($out[1][0]) && strstr($title, 'tmall.com天猫')) {
                    $item_type = 1;
                }
            }
        }
        return $item_type;
    }

    /**
     * 根据地址抓取淘宝页面html代码
     * @param string $url 地址
     * @param array $httpheader CURLOPT_HTTPHEADER信息
     * @return boolean
     */
    public function getTaoBaoHtml($url, $httpheader = array(
        "User-Agent: {Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0}",
        "Accept: {text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8}",
        "Accept-Language: {zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3}",
        "Cookie:{cq=ccp%3D1; cna=a7suCzOmSTECAXgg9iCf4AtX; t=671b2069c7e8ac444da66d664a397a5f; tracknick=%5Cu4F0D%5Cu6653%5Cu8F8901; _tb_token_=nDiU1vCuzFd0; cookie2=c54709ffbe04a5ccb80283c34d6b00fa; pnm_cku822=128WsMPac%2FFS4KgNn%2BYfhzduo4U2NC0zh9cAS4%3D%7CWUCLjKhqr873bOIFQcMecSw%3D%7CWMEKRlV%2B3D9a6XWaidNWNQOSWXwaXugvQHzhxALh%7CX0YLbX78NUR2b2DHoxnIqZENQqR35TBZbfQ5vooI0b6GHZA3U1kr%7CXkdILogCr878ZK9I%2B%2FE3QjAD3lFJJaAZRA%3D%3D%7CXUeMwMR2s%2BTUQk8IPP5TNgWfUjQwonccMCxihTa0fRYgtjgfa4j6%7CXMYK7F8liOvH3hMUpzXkiaU%2FJw%3D%3D}",
    )) {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        // 设置 url
        curl_setopt($ch, CURLOPT_URL, $url);
        //构造IP
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:127.0.0.1', 'CLIENT-IP:127.0.0.0'));
        //构造来路
        curl_setopt($ch, CURLOPT_REFERER, "http://www.taobao.com/ ");
        // 设置浏览器的特定header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
        // 页面内容我们并不需要
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        // 只需返回HTTP header
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 返回结果，而不是输出它
        //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        ob_start();
        curl_exec($ch);
        $html = ob_get_contents();
        ob_end_clean();
        curl_close($ch);
        return $html;
    }

    /**
     * 获取商品销量
     * @param type $product_id 商品ID
     * @return int
     */
    public function getSales($product_id = '') {
        $sales = 0;
        if (empty($product_id)) {
            if (empty($this->productId)) {
                return $sales;
            } else {
                $product_id = $this->productId;
            }
        }
        $json = $this->getHwsMobileTaobaoApi($product_id);
        if (is_array($json)) {
            if (is_array($json) && !empty($json)) {
                $apiStack = json_decode($json['data']['apiStack'][0]['value'], true);
                if (isset($apiStack['data']['itemInfoModel']['totalSoldQuantity'])) {
                    return $apiStack['data']['itemInfoModel']['totalSoldQuantity'];
                }
            }
        }
        return $sales;
    }

    /**
     * 得到单个商品信息
     * @param type $product_id 商品id
     * @return array|
     */
    public function getItem($product_id = '') {
        if (empty($product_id)) {
            if (!empty($this->productId)) {
                $product_id = $this->productId;
            } else {
                return false;
            }
        } else {
            $this->productId($product_id);
        }
        $cacheKey = md5('TaobaoApi_getItem_' . $product_id);
        $cache = Yii::app()->cache->get($cacheKey);
        if (!empty($cache)) {
            return $cache;
        }
        //返回数据
        $data = $this->getShopInfo(); //商品基本信息
        //店铺等级
        $data['credit_score'] = $this->getGrade();
        //销量
        $data['sales'] = $this->getSales($product_id);
        //店铺类型
        $data['item_type'] = $this->getShopType($product_id);
        //缓存下，如果多次抓取，不用每次都那么久，目标数据不会那么快变动
        Yii::app()->cache->set($cacheKey, $data, 3000);
        return $data;
    }

    /**
     * 获取商品基本信息
     * @param type $product_id 商品ID
     * @return array
     */
    public function getShopInfo($product_id = '') {
        $shopInfo = array();
        if (empty($product_id)) {
            if (empty($this->productId)) {
                return $shopInfo;
            } else {
                $product_id = $this->productId;
            }
        }
        $itemData = $this->productId($product_id)->method('taobao.item.get')->fields('detail_url,title,nick,location,item_img,price,pic_url')->getData();
        if (isset($itemData['item']['title']) && $itemData['item']['title']) {
            $shopInfo['product_id'] = $this->productId;
            $shopInfo['title'] = $itemData['item']['title'];
            //旺旺
            $shopInfo['nick'] = $itemData['item']['nick'];
            $shopInfo['detail_url'] = $this->getShopType($product_id) ? "http://detail.tmall.com/item.htm?id={$product_id}" : "http://item.taobao.com/item.htm?id={$product_id}";
            $shopInfo['pic_url'] = $itemData['item']['pic_url']; //单张图片
            $shopInfo['images'] = array();
            //全部商品介绍图片
            if ($itemData['item']['item_imgs']['item_img']) {
                foreach ($itemData['item']['item_imgs']['item_img'] AS $key => $value) {
                    $shopInfo['images'][$key] = $value['url'];
                }
            }
            $shopInfo['location'] = '';
            //省
            $shopInfo['province'] = $itemData['item']['location']['state'];
            //城市
            $shopInfo['city'] = $itemData['item']['location']['city'];
            //原价
            $shopInfo['p_price'] = $itemData['item']['price'];
            //商品活动原价
            $shopInfo['promo_price'] = 0;
            $promotion = $this->method('taobao.ump.promotion.get')->fields('detail_url,title,nick,location,item_img,price,pic_url')->getData();
            if (!empty($promotion)) {
                if (isset($promotion['promotions']['promotion_in_item']['promotion_in_item'][0]['item_promo_price'])) {
                    $shopInfo['promo_price'] = $promotion['promotions']['promotion_in_item']['promotion_in_item'][0]['item_promo_price'];
                } else {
                    $shopInfo['promo_price'] = $promotion['promotions']['promotion_in_item']['promotion_in_item']['item_promo_price'] ? $promotion['promotions']['promotion_in_item']['promotion_in_item']['item_promo_price'] : 0;
                }
            }
        } else {
            //走淘宝手机api
            $json = $this->getHwsMobileTaobaoApi($product_id);
            if (is_array($json)) {
                $apiStack = json_decode($json['data']['apiStack'][0]['value'], true);
                $shopInfo['product_id'] = $json['data']['itemInfoModel']['itemId'];
                $shopInfo['title'] = $json['data']['itemInfoModel']['title'];
                //旺旺
                $shopInfo['nick'] = $json['data']['seller']['nick'];
                $shopInfo['detail_url'] = $this->getShopType($product_id) ? "http://detail.tmall.com/item.htm?id={$product_id}" : "http://item.taobao.com/item.htm?id={$product_id}";
                $shopInfo['pic_url'] = $json['data']['itemInfoModel']['picsPath'][0]; //单张图片
                $shopInfo['images'] = $json['data']['itemInfoModel']['picsPath']; //多张图片
                $shopInfo['location'] = $json['data']['itemInfoModel']['location'];
                //省
                $shopInfo['province'] = '';
                //城市
                $shopInfo['city'] = '';
                $shopInfo['p_price'] = $apiStack['data']['itemInfoModel']['priceUnits'][1]['price'] ? $apiStack['data']['itemInfoModel']['priceUnits'][1]['price'] : $apiStack['data']['itemInfoModel']['priceUnits'][0]['price'];
                $shopInfo['promo_price'] = $apiStack['data']['itemInfoModel']['priceUnits'][0]['price'];
                if (strpos($shopInfo['p_price'], '-')) {
                    $shopInfo['p_price'] = explode('-', $shopInfo['p_price']);
                    $shopInfo['p_price'] = $shopInfo['p_price'][0];
                }
                if (strpos($shopInfo['promo_price'], '-')) {
                    $shopInfo['promo_price'] = explode('-', $shopInfo['promo_price']);
                    $shopInfo['promo_price'] = $shopInfo['promo_price'][0];
                }
            }
        }
        return $shopInfo;
    }

    /**
     * 获取店铺等级
     * @param type $product_id 商品ID
     * @return int
     */
    public function getGrade($product_id = '') {
        if (empty($product_id)) {
            if (empty($this->productId)) {
                return 0;
            } else {
                $product_id = $this->productId;
            }
        }
        $json = $this->getHwsMobileTaobaoApi($product_id);
        if (is_array($json)) {
            if (is_array($json) && !empty($json)) {
                if (isset($json['data']['seller']['creditLevel'])) {
                    return $json['data']['seller']['creditLevel'];
                }
            }
        }
        return 0;
    }

    /**
     * 获取手机淘宝Api接口数据
     * @staticvar array $_HwsMobileTaobaoApi
     * @param type $product_id 商品ID
     * @return string|array
     */
    public function getHwsMobileTaobaoApi($product_id) {
        static $_HwsMobileTaobaoApi = array();
        if (empty($product_id)) {
            return '';
        }
        if (isset($_HwsMobileTaobaoApi[$product_id])) {
            return $_HwsMobileTaobaoApi[$product_id];
        }
        $html = $this->getTaoBaoHtml("http://hws.m.taobao.com/cache/wdetail/5.0/?id={$product_id}");
        if (strlen(trim($html))) {
            $json = json_decode($html, true);
            return $json;
        }
        return '';
    }

}
